package cn.le.config;

import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 项目名  spring-boot
 * Created by lansp
 * Created at 2018/6/5
 * 描述:
 */
@Configuration
public class MongoConfig {

	/**
	 * 覆盖stirng-boot 原有的MongoDbFactory bean
	 */

	@Autowired
	private MongoSettingsProperties mongoSettingsProperties;

	@Bean
	@ConfigurationProperties(prefix = "spring.data.mongodb.custom")
	MongoSettingsProperties mongoSettingsProperties() {
		return new MongoSettingsProperties();
	}

	@Bean
    MongoDbFactory mongoDbFactory(){
		//客户端配置(连接数,副本集群验证)
		MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
		builder.connectionsPerHost(mongoSettingsProperties.getConnectionPerHost());
		builder.minConnectionsPerHost(mongoSettingsProperties.getMinConnectionPerHost());
		if (StringUtils.isEmpty(mongoSettingsProperties.getReplicaSet())){
			builder.requiredReplicaSetName(mongoSettingsProperties.getReplicaSet());
		}
		MongoClientOptions mongoClientOptions = builder.build();

		//mongoDb地址列表
		List<ServerAddress> serverAddresses = new ArrayList<>();
		for (String host : mongoSettingsProperties.getHosts()) {
			Integer index = mongoSettingsProperties.getHosts().indexOf(host);
			Integer port = mongoSettingsProperties.getPorts().get(index);

			ServerAddress serverAddress = new ServerAddress(host,port);
			serverAddresses.add(serverAddress);
		}
		System.out.println("serverAddress:"+serverAddresses.toString());

		//连接认证
		List<MongoCredential> mongoCredentials = new ArrayList<>();
		if (StringUtils.isEmpty(mongoSettingsProperties.getUserName())){
			mongoCredentials.add(MongoCredential.createScramSha1Credential(
					mongoSettingsProperties.getUserName(),
					mongoSettingsProperties.getAuthenticationDatabase() != null ?  mongoSettingsProperties.getAuthenticationDatabase() : mongoSettingsProperties.getDatabase(),
					mongoSettingsProperties.getPassword().toCharArray()
			));
		}
		System.out.println("mongoCredentialList:"+mongoClientOptions);

		//创建客户端和factory
		MongoClient mongoClient = new MongoClient(serverAddresses,mongoCredentials,mongoClientOptions);
		//参数配置情况,可以在new SimpleMongoDbFactory时,增加自己需要配置参数
		MongoDbFactory mongoDbFactory = new SimpleMongoDbFactory(mongoClient,mongoSettingsProperties.getDatabase());

		return  mongoDbFactory;
	}
}
